﻿using System;
using System.Collections.Generic;
using System.Web.SessionState;
using System.Web;
using System.Linq;
using System.Data;
using System.Text;
using Omu.ValueInjecter;

namespace RDIFramework.WebApp.Modules.handler
{
    using RDIFramework.ServiceAdapter;
    using RDIFramework.WebCommon;
    using RDIFramework.BusinessEntity;
    using RDIFramework.Utilities;

    /// <summary>
    /// DataItemAdminHandler 的摘要说明
    /// </summary>
    public class DataItemAdminHandler : IHttpHandler, IRequiresSessionState
    {
        private string action
        {
            get
            {
                return RDIFramework.WebCommon.PublicMethod.GetString(getObj("action"));
            }
        }
        private object getObj(string key) { return RDIFramework.WebCommon.StringHelper.GetRequestObject(key); }
        

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            /*
            var json = HttpContext.Current.Request["json"];
            var rpm = new RequestParamModel<CiItemsEntity>(context) { CurrentContext = context, Action = context.Request["action"] };
            if (!string.IsNullOrEmpty(json))
            {
                rpm = RDIFramework.WebCommon.JSONhelper.ConvertToObject<RequestParamModel<CiItemsEntity>>(json);
                rpm.CurrentContext = context;
            }
            */

            switch (action)
            {
                case "GetCategory":  //根据字典分类代码得到相应的数据字典明细项
                    GetCategory(context);
                    break;
                case "AddDataItem":                   
                    this.AddDataItem(context);
                    break;
                case "EditDataItem":
                    this.EditDataItem(context);
                    break;
                case "GetDataItem":
                    GetDataItem(context);
                    break;
                case "DeleteDataItem":
                    DeleteDataItem(context);
                    break;
                case "AddItemDetail":
                    AddItemDetail(context);
                    break;
                case "EditItemDetail":
                    EditItemDetail(context);
                    break;
                case "DeleteItemDetail":
                    DeleteItemDetail(context);
                    break;
                default:
                    string categoryId = PublicMethod.GetString(getObj("categoryId")); //指定指定字典下的所有明细项
                    this.GetDataItemDetailById(context, categoryId);
                    break;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// 根据字典分类代码得到相应的数据字典明细项
        /// </summary>
        /// <param name="ctx"></param>
        private void GetCategory(HttpContext ctx)
        {
            string categorycode = RDIFramework.WebCommon.PublicMethod.GetString(getObj("categorycode"));

            DataTable dtItemDetail = RDIFrameworkService.Instance.ItemDetailsService.GetDTByCode(Utils.UserInfo, categorycode);
            DataRow dataRow = dtItemDetail.NewRow();
            dtItemDetail.Rows.InsertAt(dataRow, 0);
            ctx.Response.Write(RDIFramework.WebCommon.JSONhelper.ToJson(dtItemDetail));   
        }

        
        private void GetDataItem(HttpContext ctx)
        {
            ctx.Response.Write(RDIFramework.WebCommon.JSONhelper.ToJson(RDIFrameworkService.Instance.ItemsService.GetDT(Utils.UserInfo)));
        }


        private CiItemsEntity GetPageItemEntity(CiItemsEntity entity)
        {
            entity.Code = PublicMethod.GetString(getObj("Code"));
            entity.FullName = PublicMethod.GetString(getObj("FullName"));
            entity.Category = PublicMethod.GetString(getObj("vcategory"));
            entity.Description = PublicMethod.GetString(getObj("Description"));
            entity.Enabled = PublicMethod.GetString(getObj("Enabled")) == "on" ? 1 : 0;
            return entity;
        }

        #region private void AddDataItem(HttpContext ctx) 添加数据字典类别
        /// <summary>
        /// 添加数据字典类别
        /// </summary>
        /// <param name="ctx"></param>
        private void AddDataItem(HttpContext ctx)
        {
            CiItemsEntity entity = new CiItemsEntity();
            UserInfo vUser = Utils.UserInfo;
            entity = this.GetPageItemEntity(entity);
            entity.DeleteMark = 0;
            if (vUser != null)
            {
                entity.CreateBy = vUser.RealName;
                entity.CreateUserId = vUser.Id;
            }
            string statusMessage       = string.Empty;
            string statusCode          = string.Empty;
            int successFlag = 0;

            try
            {
                RDIFrameworkService.Instance.ItemsService.Add(vUser, entity, out statusCode, out statusMessage);
                if (statusCode == StatusCode.OKAdd.ToString())
                {
                    successFlag = 1;
                    ctx.Response.Write(new JsonMessage { Success = true, Data = successFlag.ToString(), Message = statusMessage }.ToString());
                }
                else
                {
                    ctx.Response.Write(new JsonMessage { Success = false, Data = successFlag.ToString(), Message = statusMessage }.ToString());
                }
            }
            catch (Exception ex)
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = successFlag.ToString(), Message = "添加数据失败！" + ex.Message }.ToString());
            }
        }
        #endregion

        #region private void EditDataItem(HttpContext ctx) 编辑数据字典类别
        /// <summary>
        /// 编辑数据字典类别
        /// </summary>
        /// <param name="ctx"></param>
        private void EditDataItem(HttpContext ctx)
        {
            UserInfo vUser = Utils.UserInfo;
            string vId = PublicMethod.GetString(getObj("KeyId"));
            CiItemsEntity entity = RDIFrameworkService.Instance.ItemsService.GetEntity(vUser, vId);
            entity = this.GetPageItemEntity(entity);
            if (vUser != null)
            {
                entity.ModifiedBy = vUser.RealName;
                entity.ModifyUserId = vUser.Id;
            }
            string statusMessage = string.Empty;
            string statusCode = string.Empty;
            int successFlag = 0;
            try
            {
                RDIFrameworkService.Instance.ItemsService.Update(vUser, entity, out statusCode, out statusMessage);

                if (statusCode == StatusCode.OKUpdate.ToString())
                {
                    successFlag = 1;
                    ctx.Response.Write(new JsonMessage { Success = true, Data = successFlag.ToString(), Message = statusMessage }.ToString());
                }
                else
                {
                    ctx.Response.Write(new JsonMessage { Success = false, Data = successFlag.ToString(), Message = statusMessage }.ToString());
                }
            }
            catch (Exception ex)
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = successFlag.ToString(), Message = "更新数据失败！" + ex.Message }.ToString());
            }     
        }
        #endregion

        #region private void DeleteDataItem(HttpContext ctx) 删除数据字典类别
        /// <summary>
        /// 删除数据字典类别
        /// </summary>
        /// <param name="ctx"></param>
        private void DeleteDataItem(HttpContext ctx)
        {
            string vId = PublicMethod.GetString(getObj("KeyId"));
            UserInfo vUser = Utils.UserInfo;
            int successFlag = 0;

            try
            {
                int returnValue = RDIFrameworkService.Instance.ItemsService.SetDeleted(Utils.UserInfo, new string[] { vId });
                
                if (returnValue>0)
                {
                    successFlag = 1;
                    ctx.Response.Write(new JsonMessage { Success = true, Data = successFlag.ToString(), Message = RDIFrameworkMessage.MSG0013 }.ToString());
                }
                else
                {
                    ctx.Response.Write(new JsonMessage { Success = false, Data = successFlag.ToString(), Message = RDIFrameworkMessage.MSG3020 }.ToString());
                }
            }
            catch (Exception ex)
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = successFlag.ToString(), Message = RDIFrameworkMessage.MSG3020 + ex.Message }.ToString());
            } 
        }
        #endregion


        private CiItemDetailsEntity GetPageItemDetailEntity(CiItemDetailsEntity entity)
        {
            entity.ItemCode     = PublicMethod.GetString(getObj("ItemCode"));
            entity.ItemName     = PublicMethod.GetString(getObj("ItemName"));
            entity.ItemValue    = PublicMethod.GetString(getObj("ItemValue"));
            entity.Description  = PublicMethod.GetString(getObj("Description"));
            entity.ItemId       = PublicMethod.GetInt(getObj("vitemId"));
            entity.ParentId     = PublicMethod.GetInt(getObj("vparentId"));
            entity.Enabled      = PublicMethod.GetString(getObj("Enabled")) == "on" ? 1 : 0;
            entity.IsPublic     = PublicMethod.GetString(getObj("IsPublic")) == "on" ? 1 : 0;
            entity.AllowEdit    = PublicMethod.GetString(getObj("AllowEdit")) == "on" ? 1 : 0;
            entity.AllowDelete  = PublicMethod.GetString(getObj("AllowDelete")) == "on" ? 1 : 0;
            return entity;
        }

        #region private void AddItemDetail(HttpContext ctx) 增加字典明细项
        /// <summary>
        /// 增加字典明细项
        /// </summary>
        /// <param name="ctx"></param>
        private void AddItemDetail(HttpContext ctx)
        {
            CiItemDetailsEntity entity = new CiItemDetailsEntity();
            UserInfo vUser = Utils.UserInfo;
            entity = this.GetPageItemDetailEntity(entity);
            entity.DeleteMark = 0;
            if (vUser != null)
            {
                entity.CreateBy = vUser.RealName;
                entity.CreateUserId = vUser.Id;
            }
            string statusMessage = string.Empty;           
            int successFlag = 0;

            try
            {
                int returnValue = RDIFrameworkService.Instance.ItemDetailsService.Add(vUser, entity, out statusMessage);
                if (returnValue > 0 )
                {
                    successFlag = 1;
                    ctx.Response.Write(new JsonMessage { Success = true, Data = successFlag.ToString(), Message = statusMessage }.ToString());
                }
                else
                {
                    ctx.Response.Write(new JsonMessage { Success = false, Data = successFlag.ToString(), Message = statusMessage }.ToString());
                }
            }
            catch (Exception ex)
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = successFlag.ToString(), Message = RDIFrameworkMessage.MSG3020 + ex.Message }.ToString());
            }
        }
        #endregion

        #region private void EditItemDetail(HttpContext ctx) 修改字典明细项
        /// <summary>
        /// 修改字典明细项
        /// </summary>
        /// <param name="ctx"></param>
        private void EditItemDetail(HttpContext ctx)
        {
            UserInfo vUser = Utils.UserInfo;
            string vId = PublicMethod.GetString(getObj("KeyId"));
            CiItemDetailsEntity entity = RDIFrameworkService.Instance.ItemDetailsService.GetEntity(vUser, vId);
            entity = this.GetPageItemDetailEntity(entity);
            if (vUser != null)
            {
                entity.ModifiedBy = vUser.RealName;
                entity.ModifyUserId = vUser.Id;
            }
            string statusMessage = string.Empty;
            int successFlag = 0;

            try
            {
                int returnValue = RDIFrameworkService.Instance.ItemDetailsService.Update(vUser, entity, out statusMessage);
                if (returnValue > 0)
                {
                    successFlag = 1;
                    ctx.Response.Write(new JsonMessage { Success = true, Data = successFlag.ToString(), Message = statusMessage }.ToString());
                }
                else
                {
                    ctx.Response.Write(new JsonMessage { Success = false, Data = successFlag.ToString(), Message = statusMessage }.ToString());
                }
            }
            catch (Exception ex)
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = successFlag.ToString(), Message = RDIFrameworkMessage.MSG3020 + ex.Message }.ToString());
            }
        }
        #endregion

        #region private void DeleteItemDetail(HttpContext ctx) 删除字典明细项
        /// <summary>
        /// 删除字典明细项
        /// </summary>
        /// <param name="ctx"></param>
        private void DeleteItemDetail(HttpContext ctx)
        {
            string vId = PublicMethod.GetString(getObj("KeyId"));
            UserInfo vUser = Utils.UserInfo;

            int successFlag = 0;
            try
            {
                int returnValue = RDIFrameworkService.Instance.ItemDetailsService.SetDeleted(Utils.UserInfo, new string[] { vId });

                if (returnValue > 0)
                {
                    successFlag = 1;
                    ctx.Response.Write(new JsonMessage { Success = true, Data = successFlag.ToString(), Message = RDIFrameworkMessage.MSG0013 }.ToString());
                }
                else
                {
                    ctx.Response.Write(new JsonMessage { Success = false, Data = successFlag.ToString(), Message = RDIFrameworkMessage.MSG3020 }.ToString());
                }
            }
            catch (Exception ex)
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = successFlag.ToString(), Message = RDIFrameworkMessage.MSG3020 + ex.Message }.ToString());
            } 
        }
        #endregion


        #region private void GetDataItem(HttpContext ctx) 得到指定字典的明细项
        private void GetDataItemDetailById(HttpContext ctx, string id)
        {
            List<CiItemDetailsEntity> list = new List<CiItemDetailsEntity>();
            DataTable dtItemDetail = RDIFrameworkService.Instance.ItemDetailsService.GetDTByValues(Utils.UserInfo
               , new string[] { CiItemDetailsTable.FieldDeleteMark, CiItemDetailsTable.FieldItemId }
               , new string[] { "0", id });

            if (dtItemDetail != null && dtItemDetail.Rows.Count > 0)
            {
                foreach (DataRow drow in dtItemDetail.Rows)
                {
                    list.Add(new CiItemDetailsEntity(drow));
                }

                ctx.Response.Write("[" + GroupJSONdata(list, 0) + "]");
            }
            else
            {
                ctx.Response.Write("[]");
            }
        }

        private List<CiItemDetailsEntity> GetGroups(List<CiItemDetailsEntity> groups, int? parentid)
        {
            return groups.FindAll(delegate(CiItemDetailsEntity gm) { return gm.ParentId == parentid; });
        }

        private string GroupJSONdata(List<CiItemDetailsEntity> groups, int? parentId)
        {
            StringBuilder sb = new StringBuilder();
            List<CiItemDetailsEntity> list = GetGroups(groups, parentId);
            string json = "";
            foreach (CiItemDetailsEntity gm in list)
            {
                json = RDIFramework.Utilities.JsonHelper.ObjectToJSON(gm);
                json = json.TrimEnd('}');
                sb.Append(json);
                sb.Append(",");
                sb.Append("\"children\":[");
                sb.Append(GroupJSONdata(groups, gm.Id.Value));
                sb.Append("]},");
            }

            return sb.ToString().TrimEnd(',');
        }
        #endregion
        
    }
}